/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ServerGUI.java
 *
 * Created on Dec 1, 2011, 6:54:24 PM
 */
package Yahtzee;
/**
 *
 * @author Mark Fedor
 */
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class ServerGUI extends javax.swing.JFrame {

    MultiServer testServer;
    Client testClient;
    ServerGUI gui;
    GUI yah;
    Executor executor;

    /** Creates new form ServerGUI */
    public ServerGUI() {
        // set up the look and feel of the gui interface to grap the prefered look of operating system
        String laf = UIManager.getSystemLookAndFeelClassName();
        try {
            UIManager.setLookAndFeel(laf);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        gui = this;
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        messagesTextArea = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        ipAddressTextBox = new javax.swing.JTextField();
        serverPortTextBox = new javax.swing.JTextField();
        startServerButton = new javax.swing.JButton();
        closeServerButton = new javax.swing.JButton();
        connectToServerButton = new javax.swing.JButton();
        messagesLabel = new javax.swing.JLabel();
        serverInfoLabel = new javax.swing.JLabel();
        selectPlayer = new javax.swing.JComboBox();
        startGame = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        messagesTextArea.setColumns(20);
        messagesTextArea.setRows(5);
        jScrollPane1.setViewportView(messagesTextArea);

        ipAddressTextBox.setText("localhost");
        ipAddressTextBox.setName("ipAddressText"); // NOI18N

        serverPortTextBox.setText("7777");
        serverPortTextBox.setName("serverPortText"); // NOI18N

        startServerButton.setText("Start Server");
        startServerButton.setName("startServerButton"); // NOI18N
        startServerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startServerButtonActionPerformed(evt);
            }
        });

        closeServerButton.setText("Close Server");
        closeServerButton.setName("closeServerButton"); // NOI18N
        closeServerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeServerButtonActionPerformed(evt);
            }
        });

        connectToServerButton.setText("Connect to Server");
        connectToServerButton.setName("connectToServerButton"); // NOI18N
        connectToServerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectToServerButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(startServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                    .addComponent(ipAddressTextBox, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                    .addComponent(serverPortTextBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                    .addComponent(connectToServerButton, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                    .addComponent(closeServerButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ipAddressTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(serverPortTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addComponent(startServerButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(closeServerButton)
                .addGap(12, 12, 12)
                .addComponent(connectToServerButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        messagesLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        messagesLabel.setText("Messages");

        serverInfoLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        serverInfoLabel.setText("Server Information");

        selectPlayer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select Player" }));

        startGame.setText("Start Game");
        startGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startGameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(serverInfoLabel)
                    .addComponent(messagesLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 897, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(250, 250, 250)
                        .addComponent(selectPlayer, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(startGame)))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(16, Short.MAX_VALUE)
                        .addComponent(serverInfoLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(messagesLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(selectPlayer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(startGame))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void startServerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startServerButtonActionPerformed
        // TODO add your handling code here:
        // Server has started
        messagesTextArea.setText("Starting Server...");
        testServer = new MultiServer(Integer.parseInt(serverPortTextBox.getText()),this);
        // add to the textarea the port of the server, and that it is currently listening
        messagesTextArea.append("\n" + "Listening..." + serverPortTextBox.getText()+"\n");
//        testServer.start();
        SwingWorker worker = new SwingWorker<MultiServer, Void>() 
        {
            @Override
             public MultiServer doInBackground() 
            {
            testServer.start();
            return testServer;
        
        }
        };
        worker.execute();
    }//GEN-LAST:event_startServerButtonActionPerformed

    private void connectToServerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectToServerButtonActionPerformed
        // TODO add your handling code here:

        testClient = new Client();


        SwingWorker work = new SwingWorker<Client, Void>() 
        {
            @Override
             public Client doInBackground() 
            {
            testClient.start(ipAddressTextBox.getText(), Integer.parseInt(serverPortTextBox.getText()),gui);
            return testClient;
        
        }
        };
        executor = Executors.newCachedThreadPool();
        executor.execute(work);
        work.execute();
        
    }//GEN-LAST:event_connectToServerButtonActionPerformed

    private void closeServerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeServerButtonActionPerformed
        // TODO add your handling code here:
        testClient.close();
//        testServer.close();
        messagesTextArea.setText("Things have closed???");
    }//GEN-LAST:event_closeServerButtonActionPerformed

    private void startGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startGameActionPerformed
        // tells the client to set up the game
        // sends the ip address of the player selected from combobox
        System.out.println(selectPlayer.getSelectedItem());

        yah = new GUI();
        testClient.startGame(selectPlayer.getSelectedItem().toString(),yah);


        SwingWorker worker = new SwingWorker<Client, Void>()
        {
            @Override
             public Client doInBackground()
            {
                System.out.println("In Background");
                testClient.processGame();
                return testClient;
            }

        };
        executor.execute(worker);
        // start up the yahtzee gui
//        yah = new GUI();
        yah.setVisible(true);
        yah.player2Label.setText(selectPlayer.getSelectedItem().toString());

        



        
       
    }//GEN-LAST:event_startGameActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ServerGUI().setVisible(true);
            }
        });
    }
    // allows you to add string items to a combo box
    public Object makeObj(final String item)  
        {
            return new Object()
            {
                public String toString()
                {
                    return item;
                }
            };
        }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton closeServerButton;
    private javax.swing.JButton connectToServerButton;
    public javax.swing.JTextField ipAddressTextBox;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messagesLabel;
    public javax.swing.JTextArea messagesTextArea;
    public javax.swing.JComboBox selectPlayer;
    private javax.swing.JLabel serverInfoLabel;
    private javax.swing.JTextField serverPortTextBox;
    public javax.swing.JButton startGame;
    public javax.swing.JButton startServerButton;
    // End of variables declaration//GEN-END:variables
}
